package com.sz.stock.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sz.stock.mapper.POSMapper;
import com.sz.stock.model.POS;
import com.sz.stock.model.POSExample;
import com.sz.stock.model.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class PosServiceImp implements IPosService {

    @Autowired
    private POSMapper posMapper;

    /**
     *  查询 持仓(LIST)
     */
    @Override
    public List<POS> selectPos1(POS pos) {
        POS pos2=null;
        POSExample example =new POSExample();
        POSExample.Criteria criteria = example.createCriteria();
        criteria.andStockPosUseridEqualTo(pos.getStockPosUserid());
        criteria.andStockPosCodeEqualTo(pos.getStockPosCode());
        List<POS> pos1= posMapper.selectByExample(example);
        return pos1;
    }

    /**
     * 查询 持仓信息 带分页
     */
    @Override
    public PageBean<POS> allPos2(int userid, int pageIndex, int pageSize, String searchCode) {
        PageHelper.startPage(pageIndex,pageSize);
        POSExample example=new POSExample();
        POSExample.Criteria criteria = example.createCriteria();
        if (searchCode!=null && !searchCode.equals("")){
            criteria.andStockPosCodeEqualTo(searchCode);
        }
        criteria.andStockPosUseridEqualTo(userid);
        List<POS> list = posMapper.selectByExample(example);
        Page<POS> plist = (Page<POS>) list;
        PageBean<POS> pb = new PageBean<>(
                plist.getTotal(), plist.getResult(),
                plist.getPageSize(), plist.getPages(), plist.getPageNum()
        );
        return pb;
    }

    /**
     * 查询 指定股票的 持仓信息
     */
    @Override
    public POS getOnePos(String code, Integer userId) {
        POS pos = null;
        POSExample example = new POSExample();
        POSExample.Criteria criteria = example.createCriteria();
        criteria.andStockPosCodeEqualTo(code).andStockPosUseridEqualTo(userId);
        List<POS> pos1 = posMapper.selectByExample(example);
        for (POS pos2 : pos1) {
            pos = pos2;
        }
        if (pos != null) {
            return pos;
        } else {
            return null;
        }

    }

    /**
     * 添加 持仓
     */
    @Override
    public int posAdd(POS pos) {
        return posMapper.insertSelective(pos);
    }

    /**
     * 修改或删除 持仓
     * (持有数量小于或等于0 则删除)
     */
    @Override
    public int posUpdate(POS pos) {
        if (pos.getStockPosTradblance() <= 0) {           //持有数量小于或等于0 则删除
            posMapper.deleteByPrimaryKey(pos.getStockPosId());  //通过主键删除
        } else {
            posMapper.updateByPrimaryKeySelective(pos);  //修改
        }
        return 0;
    }
}
